package com.situ.edu.controller;


import com.situ.edu.pojo.entity.Auth;
import com.situ.edu.pojo.entity.User;
import com.situ.edu.service.IAuthService;
import com.situ.edu.service.IUserService;
import com.situ.edu.service.impl.AuthServiceImpl;
import com.situ.edu.service.impl.UserServiceImpl;
import com.situ.edu.util.CookieUtils;
import com.situ.edu.util.JSONUtils;
import com.situ.edu.util.MyBeanUtils;
import com.situ.edu.util.Result;
import org.springframework.util.ObjectUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@WebServlet("/user")
public class UserController extends BaseController {
    private IUserService userService = new UserServiceImpl();
    private IAuthService authService = new AuthServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        
        switch (method){
            case "login"://登录、权限管理
                login(req,resp);
                break;
            case "logout"://注销(退出)，重新回到登录界面
                logout(req,resp);
                break;
            case "selectByUser":
                selectByUser(req,resp);
                break;
            case "selectAll"://获取管理员所有信息--id
                selectAll(req,resp);
                break;
            case "selectById": //用于上传图片
                selectById(req,resp);
                break;
            case "updatePass"://修改密码
                updatePass(req,resp);
                break;
            case "updatePic": //上传图片
                updatePic(req,resp);
                break;
        }
    }

    private void updatePic(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("UserController.updatePic");
        User user = MyBeanUtils.copyToBean(req, User.class);
        userService.updatePic(user);
        //Session：将数据存储到服务器端
        //获得Session对象
        HttpSession session = req.getSession();
        //从服务器中取出user数据(改变后的新数据)
        User u = (User) session.getAttribute("user");
        //把前台中的${user.image}中的数据换成新数据
        u.setImage(user.getImage());

        toJSON(resp,Result.ok("头像修改成功"));
    }

    private void selectById(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("UserController.selectById");
        String id = req.getParameter("id");
        User user = userService.selectById(Integer.parseInt(id));
        toJSON(resp,Result.ok(user));
    }

    private void updatePass(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("UserController.updatePass");
        String id = req.getParameter("id");
        String oldPass = req.getParameter("oldPassword");
        String newPass = req.getParameter("confirmPassword");

        //用户修改密码，原密码是否输入正确
        HttpSession session = req.getSession();
        User u = (User) session.getAttribute("user");
        System.out.println("原密码：" + u.getPassword());
        if (!u.getPassword().equals(oldPass)){
            toJSON(resp,Result.error("原密码输入错误"));
            return;
        }

        userService.updatePass(Integer.parseInt(id),newPass);
        toJSON(resp,Result.ok("密码修改成功"));


    }


    private void selectAll(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("UserController.selectAll");
        List<User> list = userService.selectAll();
        toJSON(resp,Result.ok(list));

    }

    private void selectByUser(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("UserController.selectByUser");
        User user = (User) userService.selectAll();
        HttpSession session = req.getSession();
        session.getAttribute("user");

    }

    private void logout(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("UserController.logout");
        HttpSession session = req.getSession();
        session.removeAttribute("user");
        session.removeAttribute("auths");

        //CookieUtils自建工具类的方法必须为静态方法，要不然引用CookieUtils无法找到方法
        Cookie cookie = CookieUtils.getCookie(req, "autoLogin");
        //退出后，清除cookie记录，方法：创建相同名称的cookie(把原有的cookie覆盖)，并设置为0
        //如果用户没有勾选自动登录，那么这个Cookie就是null,回报空指针异常，所以要加判断
        if (cookie != null){
            //设置Cookie的存活时间为0
            cookie.setMaxAge(0);
            //退出后重新登录，则重新添加cookie
            resp.addCookie(cookie);
        }

        toJSON(resp, Result.ok("退出成功"));
    }

    private void login(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("UserController.login");
        String name = req.getParameter("name");
        String password = req.getParameter("password");
        String code = req.getParameter("code");

        String regexName = "^[a-zA-Z0-9_\\u4e00-\\u9fa5\\s·]+$";
        Pattern pattern = Pattern.compile(regexName);
        Matcher matcher = pattern.matcher(name);
        if (!matcher.find()){
            JSONUtils.toJSON(resp,Result.error("用户名不能有特殊字符"));
            return;
        }

        //先判断验证码是不是正确
        //1、验证码错误，返回一个验证码错误的提示
        //2、验证码正确，再验证 验证码是不是正确
        HttpSession session = req.getSession();
        String codeInSession = (String) session.getAttribute("codeInSession");
        if (!codeInSession.equalsIgnoreCase(code)){
            toJSON(resp, Result.error("验证码错误"));
            return;
        }

        User user = userService.login(name,password);
        //使用ajax改进登录
        if (user == null){
            toJSON(resp,Result.error("用户名或者密码错误"));
            return;
        }
        if (user.getStatus() == 0){
            toJSON(resp,Result.error("该用户已被禁用，请联系管理员"));
            return;
        }


        //自动登录
        //判断有没有勾选自动登录
        String autoLogin = req.getParameter("autoLogin");
        if (!ObjectUtils.isEmpty(autoLogin)){
            Cookie cookie = new Cookie("autoLogin", user.getName() + "&" + user.getPassword());
            //设置Cookie的存活时间和绑定路径
            cookie.setMaxAge(60*60*24*7); //设置时间为1周
            cookie.setPath(req.getContextPath());
            //在响应resp中添加cookie,返回给浏览器
            resp.addCookie(cookie);
        }

        //可以让其他网页使用EL表达式
        session.setAttribute("user",user);
        List<Auth> auths = authService.selectByRole(user.getRole());
        session.setAttribute("auths",auths);
        toJSON(resp,Result.ok("登录成功"));

    }
}
